﻿using AutoMapper;
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Services.MessageNotice.Entities.Easemob.Request;
using Dora.Tools.Enums.AdminUser;
using Dora.Tools.Utility;
using Dora.Tools.Utility.Const;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 环信消息历史记录表服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class HxMsgHistoryService : DoraServiceBase, IHxMsgHistoryService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly HxMsgHistoryRepository _repository;
        private readonly HxUserContactRepository _hxUserContactRepository;
        public HxMsgHistoryService(ISugarUnitOfWork unitOfWork
            ) 
        {
            _unitOfWork = unitOfWork;
            _repository = new HxMsgHistoryRepository(unitOfWork);
            _hxUserContactRepository = new HxUserContactRepository(unitOfWork);
        }
        
        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<HxMsgHistoryEntity>> GetPageList(HxMsgHistoryQueryDto input)
        {
            var page = await _repository.GetPageList(input);
            return page;
        }

        /// <summary>
        /// 环信保存文本历史消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgTextSave(HxMsgSaveDto<MsgText> input)
        {
            return await MsgSave(input);
        }

        /// <summary>
        /// 环信保存图片消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgImgSave(HxMsgSaveDto<MsgImg> input)
        {
            return await MsgSave(input);
        }

        /// <summary>
        /// 环信保存文件消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgFileSave(HxMsgSaveDto<MsgFile> input)
        {
            return await MsgSave(input);
        }

        /// <summary>
        /// 环信保存语音消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgAudioSave(HxMsgSaveDto<MsgAudio> input)
        {
            return await MsgSave(input);
        }
        
        /// <summary>
        /// 环信保存语音消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgVideoSave(HxMsgSaveDto<MsgVideo> input)
        {
            return await MsgSave(input);
        }

        /// <summary>
        /// 环信保存位置消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> MsgLocSave(HxMsgSaveDto<MsgLoc> input)
        {
            return await MsgSave(input);
        }

        /// <summary>
        /// 环信保存文本历史消息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultDto<int>> MsgSave<T>(HxMsgSaveDto<T> input) where T:BaseMsg
        {
            if (input == null || input.body == null)
            {
                return ResultDto<int>.Error("参数传递错误");
            }

            if (string.IsNullOrEmpty(input.from) || input.to==null|| input.to.Count == 0 || string.IsNullOrEmpty(input.id))
            {
                return ResultDto<int>.Error("参数传递错误");
            }
            var existId = await _repository.ExistHxMsgId(input.id);
            if (existId)
            {
                return ResultDto<int>.Error("消息已经保存过了");
            }
            #region From
            var fromHxUserName = input.from;
            var arrFrom = fromHxUserName.Split('_');
            int fromSystemId = 0;
            var fromUserId = Guid.Empty;
            var fromNickName = "";
            var fromOrgId = 0;
            var fromOrgName = "";
            var fromAvatar = "";
            if (arrFrom.Length >= 2)
            {
                int.TryParse(arrFrom[0], out fromSystemId);
                Guid.TryParse(arrFrom[1], out fromUserId);
            }

            if (input.ext?.Count > 0)
            {
                if (input.ext.ContainsKey("FromNickName"))
                {
                    fromNickName = input.ext["FromNickName"]?.ToString();
                }
                if (input.ext.ContainsKey("FromOrgId"))
                {
                    int.TryParse(input.ext["FromOrgId"]?.ToString(), out fromOrgId);
                }
                if (input.ext.ContainsKey("FromOrgName"))
                {
                    fromOrgName = input.ext["FromOrgName"]?.ToString();
                }
                if (input.ext.ContainsKey("FromAvatar"))
                {
                    fromAvatar = input.ext["FromAvatar"]?.ToString();
                }
            }
            #endregion
            var sendTime = DateTime.Now;// ConstValue.DefautDate;
            //var convertSendTime = ConvertHelper.LongToDateTime(input.time);
            //sendTime = convertSendTime.HasValue ? convertSendTime.Value : sendTime;
            var msgHistoryList = new List<HxMsgHistoryEntity>();
            foreach (var toHxUserName in input.to)
            {
                #region To
                //var toHxUserName = input.to;
                var arrTo = toHxUserName.Split('_');
                int toSystemId = 0;
                var toUserId = Guid.Empty;
                var toNickName = "";
                var toOrgId = 0;
                var toOrgName = "";
                var toAvatar = "";
                if (arrTo.Length >= 2)
                {
                    int.TryParse(arrTo[0], out toSystemId);
                    Guid.TryParse(arrTo[1], out toUserId);
                }

                if (input.ext?.Count > 0)
                {
                    if (input.ext.ContainsKey("ToNickName"))
                    {
                        toNickName = input.ext["ToNickName"]?.ToString();
                    }
                    if (input.ext.ContainsKey("ToOrgId"))
                    {
                        int.TryParse(input.ext["ToOrgId"]?.ToString(), out toOrgId);
                    }
                    if (input.ext.ContainsKey("ToOrgName"))
                    {
                        toOrgName = input.ext["ToOrgName"]?.ToString();
                    }
                    if (input.ext.ContainsKey("ToAvatar"))
                    {
                        toAvatar = input.ext["ToAvatar"]?.ToString();
                    }
                }
                #endregion

                var entity = new HxMsgHistoryEntity();
                entity.Id = Guid.NewGuid();
                entity.FromSystemId = fromSystemId;
                entity.FromUserId = fromUserId;
                entity.FromHxUserName = fromHxUserName;
                entity.FromNickName = fromNickName;
                entity.FromOrgId = fromOrgId;
                entity.FromOrgName = fromOrgName;
                entity.FromAvatar = fromAvatar;
                entity.HxMsgId = input.id;
                entity.SendTime = sendTime;
                entity.ToSystemId = toSystemId;
                entity.ToUserId = toUserId;
                entity.ToHxUserName = toHxUserName;
                entity.ToNickName = toNickName;
                entity.ToOrgId = toOrgId;
                entity.ToOrgName = toOrgName;
                entity.ToAvatar = toAvatar;
                entity.ChatType = input.type;
                entity.MsgType = input.body.type;

                if (typeof(T) == typeof(MsgText))
                {
                    entity.MsgContent = (input.body as MsgText).msg;
                }
                else if (typeof(T) == typeof(MsgImg))
                {
                    entity.MsgContent = "[图片]";
                }
                else if (typeof(T) == typeof(MsgFile))
                {
                    entity.MsgContent = "[文件]";
                }
                else if (typeof(T) == typeof(MsgAudio))
                {
                    entity.MsgContent = "[语音]";
                }
                else if (typeof(T) == typeof(MsgVideo))
                {
                    entity.MsgContent = "[视频]";
                }
                else if (typeof(T) == typeof(MsgLoc))
                {
                    entity.MsgContent = "[位置]";
                }
                else
                {
                    entity.MsgContent = "";
                }
                entity.MsgJson = JsonConvert.SerializeObject(input);
                entity.IsDeleted = 0;
                entity.Remark = "";
                entity.CreatedTime = DateTime.Now;
                msgHistoryList.Add(entity);
            }
            var result = await _repository.BatchCreate(msgHistoryList);
            if (result >0)
            {
                await _hxUserContactRepository.SaveOrUpdateContactFromMsgHistory(msgHistoryList);
            }
            return ResultDto<int>.Success(result);
        }
    }
}
